package com.suray.attendance.connect;
import java.util.List;
import javax.ws.rs.client.*;
import javax.ws.rs.client.Invocation.Builder;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;


import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.suray.attendance.common.utils.LoggerUtil;
import com.suray.attendance.common.utils.MD5;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.stereotype.Component;

/**
 * @Author: jianglinyu
 * @CreateTime: 2023-07-12  14:47
 * @Description: 调用ERP的api的接口类
 * @Version: 1.0
 */
@CommonsLog
@Component
public class ErpApiConnect {

    public static JSONObject readOrUpdateApproveStatus(String restUrl, String serverName, List<String[]> readMaps){
        LoggerUtil.info(serverName+"操作erp的数据",ErpApiConnect.class);
        /* 設定中台整合接口位址 ：http://{中台IP}:9990/CROSS/RESTful */
        Client tClient = ClientBuilder.newClient();
        WebTarget webTarget = tClient.target(restUrl);
        /* 建立請求應用訊息，實際依作業場景決定 */
        final Builder tBuilder = webTarget.request();
        JsonObject tBodyContent = new JsonObject();
        JsonObject stdData = new JsonObject();
        JsonObject parameter = new JsonObject();
        if(readMaps != null) {
            JsonArray dataKeys = new JsonArray();
            for (String[] readMap : readMaps) {
                JsonObject condition = new JsonObject();
                condition.addProperty("doc_no", readMap[0]);
                dataKeys.add(condition);
            }
            parameter.add("data_keys", dataKeys);
        }
        stdData.add("parameter", parameter);
        tBodyContent.add("std_data", stdData);
        LoggerUtil.info(serverName+"请求erp接口的参数="+tBodyContent,ErpApiConnect.class);
        getHeaders(serverName, tBuilder);
        /* 呼叫中台，取得回傳結果 */
        Response response = tBuilder.post(Entity.entity(tBodyContent.toString(), MediaType.APPLICATION_JSON));
        return response.readEntity(JSONObject.class);
    }
    public static JSONObject query(String restUrl, String serverName, List<String[]> queryMaps, List<String[]> orderMaps,Integer pageNo) {
        LoggerUtil.info(serverName+"查询erp的数据",ErpApiConnect.class);
        /* 設定中台整合接口位址 ：http://{中台IP}:9990/CROSS/RESTful */
        Client tClient = ClientBuilder.newClient();
        WebTarget webTarget = tClient.target(restUrl);
        /* 建立請求應用訊息，實際依作業場景決定 */
        final Builder tBuilder = webTarget.request();
        JsonObject tBodyContent = new JsonObject();
        JsonObject stdData = new JsonObject();
        JsonObject parameter = new JsonObject();
        parameter.addProperty("pageSize", 5000); // TODO OAPI: page_size     注意OAPI是小写驼峰
        parameter.addProperty("pageNo", pageNo); // TODO OAPI: page_no
        parameter.addProperty("isGetSchema", false);   // TODO:切记 OAPI和自定义集成服务的基础字段名称不一样  OAPI: is_get_schema
        parameter.addProperty("isGetCount", true); // TODO OAPI: is_get_count

        if(queryMaps != null) {
            JsonArray conditions = new JsonArray();
            for (String[] queryMap : queryMaps) {
                JsonObject condition = new JsonObject();
                condition.addProperty("field_name", queryMap[0]);
                condition.addProperty("value", queryMap[1]);
                condition.addProperty("operator", queryMap[2]);
                conditions.add(condition);
            }
            parameter.add("conditions", conditions);
        }
        if(orderMaps != null) {
            JsonArray orders = new JsonArray();
            for (String[] orderMap : orderMaps) {
                JsonObject order = new JsonObject();
                order.addProperty("field_name", orderMap[0]);
                order.addProperty("order_type", orderMap[1]);
                orders.add(order);
            }
            parameter.add("orders", orders);
        }
        stdData.add("parameter", parameter);
        tBodyContent.add("std_data", stdData);
        LoggerUtil.info("查询erp参数="+tBodyContent,ErpApiConnect.class);
        getHeaders(serverName, tBuilder);
        /* 呼叫中台，取得回傳結果 */
        Response response = tBuilder.post(Entity.entity(tBodyContent.toString(), MediaType.APPLICATION_JSON));
        return response.readEntity(JSONObject.class);
    }

    public static JSONObject create(String restUrl, String serverName, String jsonData) {
        log.info(serverName+"创建工单数据");
        /* 設定中台整合接口位址 ：http://{中台IP}:9990/CROSS/RESTful */
        Client tClient = ClientBuilder.newClient();
        WebTarget webTarget = tClient.target(restUrl);
        /* 建立請求應用訊息，實際依作業場景決定 */
        final Builder tBuilder = webTarget.request();
        JsonObject tBodyContent = new JsonObject();
        JsonObject stdData = new JsonObject();
        JsonObject parameter = new JsonObject();
        if(jsonData != null) {
            JsonParser parser = new JsonParser();
            JsonElement tradeElement = parser.parse(jsonData);
            JsonArray jsonArray = tradeElement.getAsJsonArray();
            parameter.add("datas",jsonArray);
        }
        stdData.add("parameter", parameter);
        tBodyContent.add("std_data", stdData);
        LoggerUtil.info("创建erp工单的参数="+tBodyContent,ErpApiConnect.class);
        getHeaders(serverName, tBuilder);
        /* 呼叫中台，取得回傳結果 */
        Response response = tBuilder.post(Entity.entity(tBodyContent.toString(), MediaType.APPLICATION_JSON));
        return response.readEntity(JSONObject.class);
    }



    private static void getHeaders(String serverName, Builder tBuilder) {
        JsonObject tHostJsonObject = new JsonObject();
        JsonObject tSrvJsonObject = new JsonObject();

        /* 建立提供給中台的請求信封資訊 */
        MultivaluedMap<String, Object> tHeaderMap = new MultivaluedHashMap<String, Object>();
        tHeaderMap.add("digi-type", "sync");
        /* 請求方資訊 */
        tHostJsonObject.addProperty("prod", "YREPORT"); // 正式：YMES YREPORT  测试：YTS
        tHostJsonObject.addProperty("ver", "5.7");
        tHostJsonObject.addProperty("ip","192.168.1.217");
        tHostJsonObject.addProperty("id", "");
        tHostJsonObject.addProperty("timezone", "+8");
        tHostJsonObject.addProperty("timestamp", "2018071990007275");
        tHostJsonObject.addProperty("lang", "zh_CN");
        tHostJsonObject.addProperty("acct", "codetest");


        /* 服務方資訊 */
        tSrvJsonObject.addProperty("prod", "E10");
        tSrvJsonObject.addProperty("ip", "192.168.1.253");// TODO: 192.168.1.253  测试：192.168.1.217
        tSrvJsonObject.addProperty("ver", "6.0.0.3");
        tSrvJsonObject.addProperty("id", "E10_GLB_External");
        tSrvJsonObject.addProperty("name", serverName);
        tHeaderMap.add("digi-host", tHostJsonObject.toString());
        tHeaderMap.add("digi-service", tSrvJsonObject.toString());
        tHeaderMap.add("digi-data-exchange-protocol", "1.0");

        /* 產生驗證key值 */
        String tHashCode = MD5.MD5Encode(tHostJsonObject.toString() + tSrvJsonObject.toString());
        tHeaderMap.add("digi-key", tHashCode);
        tBuilder.headers(tHeaderMap);
    }



}